package user.service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import db.dbConnection;


import user.bean.UserBean;

public class UserService {
	
	dbConnection db = new dbConnection();
	public UserBean Login(UserBean user) {
		UserBean userbean = new UserBean();
		String sql="select * from user where username=?";
		Connection conn=db.getConnection();
		PreparedStatement past = null;
		try{
			past = conn.prepareStatement(sql);
			past.setString(1, user.getUsername());
			ResultSet rs = past.executeQuery();
			if (!rs.next()) {
				return null;
			}
			user.setUsername(rs.getString("username"));
			user.setPassword(rs.getString("password"));
		}catch(SQLException e){
			e.printStackTrace();
		}finally {
			db.closeConnection(conn);
		}
		return user;
	}
	
	public boolean exit(UserBean user) {
		
	   boolean flag=true;
		return flag;
	}
	
	public boolean check(UserBean user) {
		boolean flag = false;
		String sql = "select username from user";
		Connection conn = db.getConnection();
		PreparedStatement past = null;
		try {
			past = conn.prepareStatement(sql);
			ResultSet rs = past.executeQuery();
			while (rs.next()) {
				String username = rs.getString("username");
				if (username.equalsIgnoreCase(user.getUsername())) {
					return true;
				}
			}
			past.close();
			rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			db.closeConnection(conn);
		}
		return flag;
	}
	public UserBean show(UserBean userbean) {
		UserBean user = new UserBean();
		String sql = "select * from user where username = " + "'"
				+ userbean.getUsername() + "'";

		Connection conn = db.getConnection();
		PreparedStatement past = null;
		ResultSet rs = null;
		try {
			past = conn.prepareStatement(sql);
			rs = past.executeQuery();
			if (!(rs.next())) {
				return null;
			}
			user.setUsername(rs.getString("username"));
			rs.close();
			past.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		 finally {
			db.closeConnection(conn);
		}

		return user;
	}

}
